extends Node2D

@export var enemy_data : EnemyData

@onready var health_component: HealthComponent = $HealthComponent
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
@onready var state_machine: StateMachine = $StateMachine
@onready var attack_timer: Timer = $AttackTimer


#内部变量
var attack_gap : float 
var attack_damage : int 


#玩家节点
var player 
signal enemy_shoot

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	
	add_to_group("Enemy")
	
	var players = get_tree().get_nodes_in_group("Player")
	if players.size() > 0:
		player = players[0]
		
	player.player_shoot.connect(_on_player_shoot)
	
	#方便后续动态读取数据，更换动画资源
	load_enemy_data()

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	pass


func load_enemy_data() ->void:
	attack_gap = enemy_data.attack_gap
	attack_damage = enemy_data.attack_damage
	
	attack_timer.wait_time = attack_gap

func _on_player_shoot() ->void:
	health_component.take_damage(attack_damage)
	print("敌人当前血量" + str(health_component.current_health))
	
	#玩家射击之后强切状态到受伤
	state_machine.transition_to("Hurt")
	
func _on_health_component_died() -> void:
	
	animated_sprite.play("Dead")
	await animated_sprite.animation_finished	
	queue_free()


func _on_health_component_health_changed(old_value: float, new_value: float) -> void:
	state_machine.transition_to("Hurt")


func _on_attack_timer_timeout() -> void:
	state_machine.transition_to("Attack")
	print("敌人攻击了")
	enemy_shoot.emit()
